package com.bluedemokk.www;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bluedemokk.www.blue.BlueAdapter;
import com.bluedemokk.www.blue.HexUtil;
import com.bluedemokk.www.blue.OnBlueStateListener;
/**
 * Created by Administrator on 2017/10/16.
 */

public class ActivityDemo extends Activity {
    private EditText txt_bluename, txt_code;
    private Button btn_link, btn_lock,btn_unlock;
    private TextView txt_info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo_view);
        txt_code = (EditText) findViewById(R.id.txt_code);
        txt_bluename = (EditText) findViewById(R.id.txt_bluename);
        btn_link = (Button) findViewById(R.id.btn_link);
        btn_lock = (Button) findViewById(R.id.btn_lock);
        btn_unlock = (Button) findViewById(R.id.btn_unlock);
        txt_info = (TextView) findViewById(R.id.txt_info);


        initFeature();
    }

    private void initFeature() {
        System.out.println("Feature");
        System.out.println("Feature22222222222222222");

    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    private void tipsAddTxt(final String info) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String text = txt_info.getText().toString();
                txt_info.setText(text + "\r\n" + info);
            }
        });
    }
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        BlueAdapter.getInstance().init(getApplicationContext());
        initEvent();
        BlueAdapter.getInstance().setOnBlueStateListener(new OnBlueStateListener() {
            @Override
            public void onConnectedFailed(String error) {
                Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
                tipsAddTxt(error);
            }
            @Override
            public void onConnectedOK() {
                Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT).show();
                tipsAddTxt("连接成功");
                String code = txt_code.getText().toString().trim();
                byte[] msg = newBlueMessage((byte) 1, (byte) 1, code.getBytes());
                BlueAdapter.getInstance().sendMessage(HexUtil.bytesToHexString(msg));
            }
            @Override
            public void onMessageSended(byte[] bytes) {
                tipsAddTxt("已发送:" + HexUtil.bytesToHexString(bytes));
                if (bytes.length > 16) {
                    new CountDownTimer(200L, 200L) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                        }
                        @Override
                        public void onFinish() {
                            //BlueAdapter.getInstance().sendMessage("AA 02 55 0A F4");
                        }
                    }.start();
                } else if (bytes.length == 5 && bytes[0] == HexUtil.hexStringToBytes("AA")[0]
                        && bytes[1] == 2
                        && bytes[2] == HexUtil.hexStringToBytes("55")[0]
                        && bytes[3] == HexUtil.hexStringToBytes("0A")[0]
                        && bytes[4] == HexUtil.hexStringToBytes("F4")[0]) {
                } else {
                    //其它发送成功的
                }
            }
            @Override
            public void onReceiveData(byte[] data) {
                tipsAddTxt("已接收:" + HexUtil.bytesToHexString(data));
            }
        });
    }
    private void initEvent() {
        btn_link.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!checkPermission())return;
                String name = txt_bluename.getText().toString().trim();
                String code = txt_code.getText().toString().trim();
                if (code == null || name == null){
                    Toast.makeText(getApplicationContext(), "请输完整数据", Toast.LENGTH_SHORT).show();
                    return;
                }
                BlueAdapter.getInstance().needConnectDevice(name);
            }
        });
        btn_lock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BlueAdapter.getInstance().sendMessage("0x82 02 40 00 3B");
                Toast.makeText(ActivityDemo.this, "汽车加锁", Toast.LENGTH_SHORT).show();
            }
        });
        btn_unlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BlueAdapter.getInstance().sendMessage("0x82 02 08 00 73");
                Toast.makeText(ActivityDemo.this, "汽车解锁", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public boolean checkPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0+
            int permission1 = checkSelfPermission(android.Manifest.permission.BLUETOOTH);
            int permission2 = checkSelfPermission(android.Manifest.permission.BLUETOOTH_ADMIN);
            int permission4 = checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
            int permission5 = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
            //蓝牙权限
            if (permission1 != PackageManager.PERMISSION_GRANTED ||
                    permission2 != PackageManager.PERMISSION_GRANTED
                    || permission4 != PackageManager.PERMISSION_GRANTED
                    || permission5 != PackageManager.PERMISSION_GRANTED
                    ) {
                requestPermissions(new String[]{
                        android.Manifest.permission.BLUETOOTH
                        , android.Manifest.permission.BLUETOOTH_ADMIN
                        , android.Manifest.permission.ACCESS_COARSE_LOCATION
                        , android.Manifest.permission.ACCESS_FINE_LOCATION
                }, 1);
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    /**
     * @param typeId 指令id
     * @param preId 业务id
     * @param data 数据
     * typeId + length(preId+data) + preId + data +OXff
     */
    public static byte[] newBlueMessage(byte typeId,byte preId,byte[] data){
        byte length = (byte) (data.length+1);
        byte[] result = new byte[length+3];
        result[0]= typeId;
        result[1]= length;
        result[2]= preId;
        System.arraycopy(data,0,result,3,data.length);
        //胶验
        byte ox = 0;
        for(byte bt:result){
            ox += bt;
        }
        ox ^= 0xff;
        result[length+2]= ox;
        return result;
    }

//    public static void main(String[] args) {
//        byte[] msg = newBlueMessage((byte) 1, (byte) 1, "7c458fbf233f3c89".getBytes());
//        for (byte b : HexUtil.hexStringToBytes("0x82 02 08 00 73")) {
//            System.out.println("........"+b+"...........");
//        }
//
//    }


}
